package com.kang.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.Supplier;
import com.kang.pojo.SupplyAgreement;
import com.kang.pojo.SupplyAgreementItem;
import com.kang.service.IntemInformationService;
import com.kang.service.SupplierService;
import com.kang.service.SupplyAgreementItemService;
import com.kang.service.SupplyAgreementService;
import com.kang.until.FileUtil;
import com.vonechina.entity.page.AggrementItemPage;
import com.vonechina.entity.page.SupplyAgreementPage;

/**
 * 供货协议实体类
 * 
 * @author zs614
 *
 */
@Controller
@RequestMapping("supplyagreement")
@SessionAttributes({ "supplyAgreementPage" })
public class SupplyAgreementController extends com.kang.controller.Controller {
	/**
	 * 供货协议服务层
	 */
	@Resource
	private SupplyAgreementService agreementService;
	/**
	 * 供应商服务层
	 */
	@Resource
	private SupplierService supplierService;
	/**
	 * 物品服务层
	 */
	@Resource
	private IntemInformationService itemService;
	/**
	 * 供货协议物品信息服务层
	 */
	@Resource
	private SupplyAgreementItemService agreementItemService;

	/**
	 * 分页查询供货协议
	 * 
	 * @param session
	 * @param model
	 * @param supplyAgreementPage
	 *            搜索条件自动封装
	 * @return 返回jsp页面
	 */
	@RequestMapping("paginglist")
	public String listSupplyAgreementList(HttpSession session, Model model, SupplyAgreementPage supplyAgreementPage) {
		initRight(session);
		if (checkRight("查看供货协议") != SUCCESS) {
			return "basic/noRight";
		}
		model.addAttribute("isAdd", checkRight("新增供货协议") == SUCCESS);
		model.addAttribute("isEdit", checkRight("编辑供货协议") == SUCCESS);
		model.addAttribute("isDelete", checkRight("删除供货协议") == SUCCESS);
		List<SupplyAgreement> agreementList = agreementService.listAgreement(supplyAgreementPage);
		List<Supplier> supplierlist = supplierService.listAllSupplier();
		model.addAttribute("supplierlist", supplierlist);
		model.addAttribute("agreementList", agreementList);
		supplyAgreementPage.setPageUrl("supplyagreement/paginglist.do");
		model.addAttribute("page", supplyAgreementPage);
		return "basicData/supplyAgreement/listSupplyAgreement";
	}

	/**
	 * 供货协议附件下载
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @param supplyagreementid
	 */
	@RequestMapping(value = "fileDownload")
	public void downloadSupplyAgreementAnnex(HttpServletRequest request, HttpServletResponse response, Model model,
			Integer supplyagreementid) {
		SupplyAgreement agreement = agreementService.selectByPrimaryKey(supplyagreementid);
		FileUtil.download(response, FileUtil.SUPPLY_AGREEMENT_ANNEX_PATH + agreement.getProtocoenclosure(),
				agreement.getProtocoenclosure());
	}

	/**
	 * 新增供货协议
	 * 
	 * @param session
	 * @param supplyagreementannex
	 *            供货协议附件
	 * @param supplyagreement
	 *            功能供货协议实体类自动封装
	 * @return 返回json字符串
	 * @throws Exception
	 */
	@RequestMapping("add")
	@ResponseBody
	public String addSupplyAgreement(HttpSession session, MultipartFile supplyagreementannex,
			SupplyAgreement supplyagreement) throws Exception {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (checkRight("新增供货协议") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		if (supplyagreementannex.getSize() != 0) {
			String fileName = supplyagreementannex.getOriginalFilename();
			String filePath = fileName.substring(0, fileName.lastIndexOf(".")) + System.currentTimeMillis()
					+ fileName.substring(fileName.lastIndexOf("."));
			supplyagreementannex.transferTo(new File(FileUtil.SUPPLY_AGREEMENT_ANNEX_PATH + filePath));
			supplyagreement.setProtocoenclosure(filePath);
		}
		supplyagreement.setProtocolcode(agreementService.generatoCode());
		SimpleDateFormat simp = new SimpleDateFormat("yyyy-MM-dd");
		supplyagreement.setCreatepersonid((Integer) session.getAttribute("userID"));
		supplyagreement.setLastpersonid((Integer) session.getAttribute("userID"));
		supplyagreement.setStarttime(simp.parse(supplyagreement.getStarttimestr()));
		supplyagreement.setEndtime(simp.parse(supplyagreement.getEndtimestr()));
		supplyagreement.setLastprocessingtime(new Date());
		supplyagreement.setCreatedate(new Date());
		int a = agreementService.insertSelective(supplyagreement);
		if (a > 0) {
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 更新供货协议
	 * 
	 * @param session
	 * @param supplyagreementannex
	 *            供货协议附件
	 * @param itemPrice
	 *            供货协议物品价格
	 * @param itemIds
	 *            供货协议物品ID
	 * @param supplyagreement
	 *            供货协议实体类自动封装
	 * @return 返回json字符串
	 * @throws Exception
	 */
	@RequestMapping("update")
	@ResponseBody
	public String updateSupplyAgreement(HttpSession session, MultipartFile supplyagreementannex, Long itemPrice[],
			Integer itemIds[], SupplyAgreement supplyagreement) throws Exception {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (checkRight("编辑供货协议") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		if (supplyagreementannex.getSize() != 0) {
			String fileName = supplyagreementannex.getOriginalFilename();
			String filePath = fileName.substring(0, fileName.lastIndexOf(".")) + System.currentTimeMillis()
					+ fileName.substring(fileName.lastIndexOf("."));
			supplyagreementannex.transferTo(new File(FileUtil.SUPPLY_AGREEMENT_ANNEX_PATH + filePath));
			supplyagreement.setProtocoenclosure(filePath);
		}
		agreementItemService.deleteAgreementItem(supplyagreement.getSupplyagreementid(), itemIds);
		if (itemIds != null) {
			for (int i = 0; i < itemIds.length; i++) {
				SupplyAgreementItem item = new SupplyAgreementItem();
				item.setSupplyagreementid(supplyagreement.getSupplyagreementid());
				item.setIteminformationid(itemIds[i]);
				item.setPurchaseprice(itemPrice[i]);
				if (agreementItemService.selectAgreementItem(supplyagreement.getSupplyagreementid(),
						itemIds[i]) == null) {
					agreementItemService.insertSelective(item);
				} else {
					agreementItemService.updateAgreementItem(item);
				}
			}
		}
		SimpleDateFormat simp = new SimpleDateFormat("yyyy-MM-dd");

		supplyagreement.setStarttime(simp.parse(supplyagreement.getStarttimestr()));
		supplyagreement.setEndtime(simp.parse(supplyagreement.getEndtimestr()));
		supplyagreement.setLastpersonid((Integer) session.getAttribute("userID"));
		supplyagreement.setLastprocessingtime(new Date());

		int a = agreementService.updateByPrimaryKeySelective(supplyagreement);
		if (a > 0) {
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 删除供货协议
	 * 
	 * @param session
	 * @param request
	 * @param supplyagreementid
	 *            供货协议ID
	 * @return 返回json字符串
	 */
	@RequestMapping("delete")
	@ResponseBody
	public String deleteSupplyAgreement(HttpSession session, HttpServletRequest request, Integer supplyagreementid) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (checkRight("删除供货协议") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		int a = agreementService.deleteByPrimaryKey(supplyagreementid);
		if (a > 0) {
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 前往供货协议修改界面
	 * 
	 * @param session
	 * @param model
	 * @param supplyagreementid
	 *            供货协议ID
	 * @return
	 */
	@RequestMapping("toUpdate")
	public String toUpdateSupplyAgreement(HttpSession session, Model model, Integer supplyagreementid) {
		initRight(session);
		model.addAttribute("isEdit", checkRight("编辑供货协议") == SUCCESS);
		SupplyAgreement supplyagreement = agreementService.selectByPrimaryKey(supplyagreementid);
		List<SupplyAgreementItem> s_iteminfolist = agreementItemService.s_iteminfo(supplyagreementid);
		model.addAttribute("s_iteminfolist", s_iteminfolist);
		model.addAttribute("supplyagreement", supplyagreement);
		model.addAttribute("supplierlist", supplierService.listAllSupplier());
		return "basicData/supplyAgreement/editSupplyAgreement";
	}

	/**
	 * 获取编辑供货协议时可用物品信息
	 * 
	 * @param session
	 * @param model
	 * @param itemPage
	 *            搜索条件自动封装
	 * @return 返回json字符串
	 */
	@RequestMapping("listItemforSypplyAgreement")
	@ResponseBody
	public String listItemforSypplyAgreement(HttpSession session, Model model, AggrementItemPage itemPage) {
		List<SupplyAgreementItem> iteminfolist = agreementItemService.selectNotAddItem(itemPage);
		AjaxResult result = new AjaxResult();
		result.setRows(iteminfolist);
		result.setTotal(itemPage.getRows());
		return JSON.toJSONString(result);
	}
}
